#!/usr/bin/perl -w
#
##############################################################################
#	Author: eric keller
#	Email:	ekeller@hamilton-medical.ch
#	script name: grabit.pl
#	Project:	ngwpgrabber
#
#	Description:
#################
#	This script does
#
#
# 	Notice:
#################
#
#
#
# 	Return Values:
##################
#
#	param_error = 1 (wrong script parameter)
#	system_error = 2 (failed to open file does not exist)
#	others = 3 (other errors, trow errors...)
#	conferror = 4 (the gen.cfg file contains error)
#
#	Example(s):
#################
#
# ~> grabit.pl -h
#
#	Change Logs:
#################
#
#	on 27.01.2011		by eric keller
#		* initial version of the script
#
# 	TODO:
#################
#	high priority:
#		+
#
#	low priority:
#		*
#		*
#
##############################################################################

#/----------------------------------------------------------------------------\
#| imports
#\----------------------------------------------------------------------------/
use strict;
use File::Path;
use File::Copy;
use File::Basename;
use Time::Local;

$| = 1;

#/----------------------------------------------------------------------------\
#| globals
#\----------------------------------------------------------------------------/
# this global variable is initialised by the value
# contained in the ngwpgrabber.ini file
my %ngwpgrabini = ();
# contains the url to the national geographic photos
my @urllist = ();

# error codes
my $success     = 0;
my $retparamerr = 1;
my $retsyserr   = 2;
#/----------------------------------------------------------------------------\
#| functions
#\----------------------------------------------------------------------------/
###
## this function reads from a file and returns an array of lines.
#
sub read_from_file {
	my $filename = $_[0];
	my @lines;

	open( RF, "$filename" ) or die("No such file $filename...\n");
	@lines = <RF>;
	close(RF);
	return @lines;
}

my @useragents   = (
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009020519 Ubuntu/9.04 (jaunty) Firefox/3.0.6',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko/2009033100 Ubuntu/9.04 (jaunty) Firefox/3.0.8',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 3.5.30729)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)'
);
my $rand_agent_number = int(rand(@useragents));

# this function takes a filename containing the configuration settings
# the filename contains text settings.
#
# every setting is given as following
# [mysetting]=the_setting_value
# the # at the begining of the line define the line as a comment
#
# returns the %settings hash containing all the configuration elements
sub configurator($) {
	my $filename = $_[0];
	my $i        = 0;
	my @lines    = ();
	my %settings = ();

	@lines = read_from_file($filename);

	#print "@lines \n"; # debug
	foreach $i (@lines) {
		if ( $i !~ m/^#.*/ and $i !~ m/^\n/ ) 
		{
			$i =~ m/\[(.*)\]=(.*)/;

			#print "$1 => $2\n"; #debug
			if ( defined $1 )
			{
				if ( $1 ne "" and $2 ne "" ) 
				{
					$settings{$1} = $2;
				}
				else 
				{
					print STDERR
"line '$i' does not have the good settings format it will be ignored\n";
				}
			}
		}
		else
		{
			next;
		}
	}
	return %settings;
}

#use_wget($url, $id)
sub use_wget($$) {
    my $url          = shift;
    my $file         = shift;
    my $wgetquiet    = "";#($verbose < 2) ? '--quiet' : '';
    my $wgetusragent = "--user-agent=\"$useragents[$rand_agent_number]\"";
    my $wgetoptions  = "-nc --random-wait --no-cache --timeout=$ngwpgrabini{wget_timeout}";
    #my $proxycommand = "set http_proxy=\"$http_proxy\"";

    my $wgetcommand = "wget $url $wgetoptions $wgetusragent -O $file $wgetquiet";

    # use the Tor proxy
    #$wgetcommand = "$proxycommand; $wgetcommand" if $enableproxy;
    #print "wgetcommand: $wgetcommand\n" if ($verbose > 1);
	#print "wgetcommand: wget $url $wgetoptions $wgetusragent -O $file $wgetquiet\n";
    if ( 0 != system($wgetcommand) ) {
        warn("some problem occured when calling system\n");# if ($verbose > 1);
        #return $retsyserr;
    } else { 
        chmod( 0666, $file );
    }
    return $success;
}


# this function filter out the given array of lines, to the previous photo url
#
# param 1: is a reference on an array containing the source code of the current page.
#
# return a string containing the previous url
sub get_previous_photo_url($)
{
	my $ref_on_lines = shift;
	my @tmplines = @{$ref_on_lines};
	my @grepped = grep(/$ngwpgrabini{'regexp_previous_photo'}/, @tmplines);
	my $previous_url = 'previous_url_not_found'; 
	if (exists $grepped[0])
	{
		$grepped[0] =~ m/$ngwpgrabini{'regexp_previous_photo'}/;
		if (defined $1)
		{
			$previous_url = $1;
			#print "PREVIOUS URL=$ngwpgrabini{'baseurl'}$previous_url\n";
		}
		else
		{
			print "dollar 1 was not defined\n";
		}		
	}
	return $previous_url;
}

# this function filter out the given array of lines, to the current photo url
#
# param 1: is a reference on an array containing the source code of the current page.
# param 2: is a pattern to filter out
#
# return a string containing the current photo url
sub get_photo_url($$)
{
	my $ref_on_lines = shift;
	my $pattern = shift;
	my @tmplines = @{$ref_on_lines};	
	my @grepped = grep(/$pattern/, @tmplines);
	my $photo_url = 'photo_url_not_found';

	if (exists $grepped[0])
	{
		$grepped[0] =~ m/$pattern/;
		if (defined $1)
		{
			$photo_url = $1;
			#print "PHOTO URL=$photo_url\n";
		}
	}
	
	return $photo_url;
}


sub create_url_list($)
{
	my $nbr_of_url = shift;
	my $index = 0;
	# assume that each previous photo is added at the head of the list like a stack
	my $base_url = $urllist[0];
	print "${base_url}\n";
	my $previous_url = '';
	my $photo_url = '';
	my @tmplines = ();
	
	for($index = 0; $index < $nbr_of_url; $index++)
	{
		print "get the $index url from $base_url\n";
		# wget the base_url
		use_wget("$base_url", "./tmp/$index");
		@tmplines = read_from_file("./tmp/$index");
		$previous_url = get_previous_photo_url(\@tmplines);
		print "previous url: $previous_url\n";
		$photo_url = get_photo_url(\@tmplines, $ngwpgrabini{'regexp_download_wp'});
		#case there is no wallpaper link
		if ('photo_url_not_found' eq $photo_url)
		{
			print "photo_url_not_found get the displayed photo\n";
			$photo_url = get_photo_url(\@tmplines, $ngwpgrabini{'regexp_download_photo'});
		}
		
		print "photo url: $photo_url\n";
		use_wget("$photo_url", "./photos/$index.jpg");
		unshift(@urllist, "$ngwpgrabini{'baseurl'}$previous_url");
		# update the base url
		$base_url = $urllist[0];
	}
	
}


# this function does get the photo given by the url
# argument 1: the url containing the complete path to the wallpaper_photo
#
sub get_wallpaper_photo($)
{
	my $photo_url = shift;
	
	
}

# script entry point
sub main() {
	%ngwpgrabini = configurator("./ngwpgrabber.ini");
	#initialize the url_list with the base url
	@urllist = ("$ngwpgrabini{'baseurl'}/$ngwpgrabini{'photooftheday'}");

	#for my $key ( keys %ngwpgrabini ) {
	#	my $value = $ngwpgrabini{$key};
	#	print "$key => $value\n";
	#}
	print "URLLISTE INIT:$urllist[0]\n";
	create_url_list(300);
}

#/----------------------------------------------------------------------------\
#| enty point
#\----------------------------------------------------------------------------/
main
